import sys

from PyQt5 import QtGui
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import *
from gui import cloud
from gui import correct
from gui import error as error
from gui import mainwindow
from gui import warning
from gui import loader
from manage.options import *
from analysis.chart import *
from reptile.obtain import WorkPath


class ErrorWindow(QMainWindow):
    def __init__(self, message='未知错误', parent=None):
        super(ErrorWindow, self).__init__(parent)
        self.ui = error.Ui_Form()
        self.ui.setupUi(self, message)

    def cancel(self):
        self.close()


class WarningWindow(QMainWindow):
    def __init__(self, parent=None):
        super(WarningWindow, self).__init__(parent)
        self.ui = warning.Ui_Waring()
        self.ui.setupUi(self)

    def cancel(self):
        self.close()  # 关闭

    def notarize(self):
        sys.exit(0)


class CorrectWindow(QMainWindow):
    def __init__(self, parent=None):
        super(CorrectWindow, self).__init__(parent)
        self.ui = correct.Ui_Form()
        self.ui.setupUi(self)

    def cancel(self):
        self.close()


class CloudWindow(QMainWindow):
    def __init__(self, parent=None):
        super(CloudWindow, self).__init__(parent)
        self.ui = cloud.Ui_Form()
        self.ui.setupUi(self, WorkPath.work_dir + r'\reptile' + r"\word_cloud.png")


class LoaderWindow(QMainWindow):
    def __init__(self, parent=None):
        super(LoaderWindow, self).__init__(parent)
        self.ui = loader.Ui_Form()  # u1.(u1中的类Ui_Form)
        self.ui.setupUi(self, )
        self.path = WorkPath.work_dir + r'\analysis'

    def jump_cloud(self):
        self.cloud = CloudWindow()
        self.cloud.show()

    def jump_tip(self):
        self.warning = WarningWindow()
        self.warning.show()

    def load_check(self, role, num, password):
        if Check.password(role, num, password) and password != 'none':
            self.mainwindow = MainWindow()
            if role == 'student':
                self.mainwindow.button_alter.deleteLater()
                self.mainwindow.button_import.deleteLater()
                self.mainwindow.button_delete.deleteLater()
                self.mainwindow.button_insert.deleteLater()
                self.mainwindow.button_export.deleteLater()
                x = ['数据结构', '普通物理', '数学分析', '微机原理', '操作系统', '数据库原理', '编译原理', '程序设计']
                data = Search.row('score4', num)
                data2 = []
                for i in data:
                    data2.append(i[1])
                Draw.histogram(x, data2, path=self.path + r'\student1.png')

                x = [1, 2, 3, 4]
                data = Search.for_avg('my_avg', num)
                data = data[1:]
                c = 1
                data2 = []
                data3 = []
                sclass = Search.one('student', 'sclass', num)
                sdept = Search.one('student', 'sdept', num)
                for i in data:
                    data2.append(Avg.ranking('classes', 'my_avg', sclass, i, c))
                    data3.append(Avg.ranking('dept', 'my_avg', sdept, i, c))
                    c += 1
                Draw.line(x, data2, data3, chart_name='排名变化', y_label='排名', x_label='学期',
                          path=self.path + r'\student2.png')

                data2 = Search.for_avg('class_avg', sclass)
                data3 = Search.for_avg('dept_avg', sdept)
                data2 = data2[1:]
                data3 = data3[1:]
                Draw.line(x, data, data2, data3, chart_name='平均分变化', y_label='成绩', x_label='学期',
                          path=self.path + r'\student3.png')

                self.mainwindow.label_32.setPixmap(
                    QtGui.QPixmap(self.path + r'\student1.png'))
                self.mainwindow.label_30.setPixmap(
                    QtGui.QPixmap(self.path + r'\student2.png'))
                self.mainwindow.label_31.setPixmap(
                    QtGui.QPixmap(self.path + r'\student3.png'))
            elif role == 'teacher':
                self.mainwindow.button_import.deleteLater()
                self.mainwindow.button_delete.deleteLater()
                self.mainwindow.button_insert.deleteLater()
                self.mainwindow.button_export.deleteLater()

                cnum = Search.one('teacher', 'cnum', num)
                data = Avg.persentage('score4', 'course', cnum)
                labels = ['<60', '>60', '>70', '>80', '>90']
                for i in range(1, 5):
                    if data[i] == 0:
                        labels.pop(i)
                        data.pop(i)
                Draw.pie(data, labels, chart_name='课程分布',
                         path=self.path + r'\teacher1.png')

                tdept = Search.one('teacher', 'tdept', num)
                data = Avg.persentage('score4', 'dept', tdept)
                Draw.pie(data, labels, chart_name='学院分布',
                         path=self.path + r'\teacher2.png')

                j = 1
                data = []
                data2 = []
                while j <= 4:
                    pre_ans1 = Search.by_course(f'score{j}', cnum)
                    pre_ans2 = Search.by_dept(f'score{j}', tdept)
                    ans = []
                    ans2 = []
                    for i in pre_ans1:
                        ans.append(i[2])
                    for i2 in pre_ans2:
                        ans2.append(i2[2])
                    data.append(sum(ans) / len(ans))
                    data2.append(sum(ans2) / len(ans2))
                    j += 1

                x = [1, 2, 3, 4]
                Draw.line(x, data, data2, chart_name='变化情况', labels=['课程', '学院'], y_label='分数',
                          path=self.path + r'\teacher3.png')

                self.mainwindow.label_32.setPixmap(
                    QtGui.QPixmap(self.path + r'\teacher1.png'))
                self.mainwindow.label_30.setPixmap(
                    QtGui.QPixmap(self.path + r'\teacher2.png'))
                self.mainwindow.label_31.setPixmap(
                    QtGui.QPixmap(self.path + r'\teacher3.png'))
            elif role == 'academic':
                x = ['cs', 'is', 'ma']
                data = Search.col('dept_avg', 'period4')
                Draw.histogram(x, data, x_label='学院', y_label='分数', chart_name='学院平均',
                               path=self.path + r'\academic1.png')

                pre_ans1 = Search.col('my_avg', 'period4')
                data = Avg.percentage_list(pre_ans1)
                labels = ['<60', '>60', '>70', '>80', '>90']
                print(data)
                for i in range(1, 5):
                    if data[i] == 0:
                        labels.pop(i)
                        data.pop(i)
                Draw.pie(data, label=labels, chart_name='全部学生分布',
                         path=self.path + r'\academic2.png')

                data = Search.col('class_avg', 'period4')
                x = [i for i in range(1, 11)]
                Draw.histogram(x, data, x_label='班号',
                               y_label='成绩', chart_name='班级平均分', path=self.path + r'\academic3.png')

                self.mainwindow.label_32.setPixmap(
                    QtGui.QPixmap(self.path + r'\academic1.png'))
                self.mainwindow.label_30.setPixmap(
                    QtGui.QPixmap(self.path + r'\academic2.png'))
                self.mainwindow.label_31.setPixmap(
                    QtGui.QPixmap(self.path + r'\academic3.png'))

            self.mainwindow.show()
            self.close()
        else:
            self.err = ErrorWindow('密码或用户名错误')
            self.err.show()


class MainWindow(QMainWindow, mainwindow.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.stackedWidget.setCurrentIndex(0)

    def analyze(self):
        self.stackedWidget.setCurrentIndex(0)
        # self.button_import.deleteLater()删除控件

    def search(self):
        self.stackedWidget.setCurrentIndex(1)

    def alter(self):
        self.stackedWidget.setCurrentIndex(3)

    def insert(self):
        self.stackedWidget.setCurrentIndex(2)

    def delete(self):
        self.stackedWidget.setCurrentIndex(4)

    def fun_import(self, table_name):
        self.stackedWidget.setCurrentIndex(5)

    def export(self):
        self.stackedWidget.setCurrentIndex(6)

    def jump_tip(self):
        self.warning = WarningWindow()
        self.warning.show()

    def for_avg(self, table_name='my_avg', num='96001'):
        ans = Search.for_avg(table_name, num)
        if len(ans) == 0:
            self.err = ErrorWindow('数据库错误')
            self.err.show()
        else:
            self.avg_table.setRowCount(1)
            self.avg_table.setColumnCount(len(ans))
            labels = Db.get_field_name(f'{table_name}')
            self.avg_table.setHorizontalHeaderLabels(labels)
            for i in range(len(ans)):
                data = QTableWidgetItem(str(ans[i]))
                data.setFont(QFont('Arial', 12))
                self.avg_table.setItem(0, i, data)

    def for_table(self, table_name='student'):
        ans = Search.by_table(table_name)
        if len(ans) == 0:
            self.err = ErrorWindow('数据库错误')
            self.err.show()
        else:
            self.table_table.setRowCount(len(ans))
            self.table_table.setColumnCount(len(ans[0]))
            labels = Db.get_field_name(f'{table_name}')
            self.table_table.setHorizontalHeaderLabels(labels)
            for i in range(len(ans)):
                for j in range(len(ans[0])):
                    data = QTableWidgetItem(str(ans[i][j]))
                    data.setFont(QFont('Arial', 12))
                    self.table_table.setItem(i, j, data)

    def for_one(self, target_table='student', target_key='sname', target_num='96001'):
        ans = Search.one(target_table, target_key, target_num)
        if len(ans) == 0:
            self.err = ErrorWindow('数据库错误')
            self.err.show()
        else:
            self.one_table.setRowCount(1)
            self.one_table.setColumnCount(1)
            data = QTableWidgetItem(str(ans))
            data.setFont(QFont('Arial', 12))
            self.one_table.setItem(0, 0, data)

    def for_row(self, table_name='student', target_num='96001'):
        ans = Search.row(table_name, target_num)
        if len(ans) == 0:
            self.err = ErrorWindow('数据库错误')
            self.err.show()
        else:
            self.row_table.setRowCount(len(ans))
            self.row_table.setColumnCount(len(ans[0]))
            labels = Db.get_field_name(f'{table_name}')
            self.row_table.setHorizontalHeaderLabels(labels)
            for i in range(len(ans)):
                for j in range(len(ans[0])):
                    data = QTableWidgetItem(str(ans[i][j]))
                    data.setFont(QFont('Arial', 12))
                    self.row_table.setItem(i, j, data)

    def alter_check(self, table_name, key_name, value, target_key, target):
        if table_name.startswith("score"):
            value = eval(value)
            target = eval(target)
        whether = Alter.update(table_name, key_name, value, target_key, target)
        self.sucees_check(whether)

    def insert_score_check(self, snum, cnum, score, year):
        whether = Insert.ins_sc(snum, cnum, score, year)
        self.sucees_check(whether)

    def insert_course_check(self, cnum, cname, ctime, cplace):
        whether = Insert.ins_co(cnum, cname, ctime, cplace)
        self.sucees_check(whether)

    def insert_student_check(self, snum, sname, sdept, sclass, sexual, code):
        whether = Insert.ins_st(snum, sname, sdept, sclass, sexual, code)
        self.sucees_check(whether)

    def insert_teacher_check(self, tnum, tname, tdept, cnum, age, sexual, code):
        whether = Insert.ins_te(tnum, tname, tdept, cnum, age, sexual, code)
        self.sucees_check(whether)

    def insert_academic_check(self, anum, aname, age, sexual, code):
        whether = Insert.ins_ac(anum, aname, age, sexual, code)
        self.sucees_check(whether)

    def delete_row_check(self, table_name, key_name, value):
        whether = Delete.del_row(table_name, key_name, value)
        self.sucees_check(whether)

    def delete_table_check(self, table_name):
        whether = Delete.del_table(table_name)
        self.sucees_check(whether)

    def import_check(self, path, table_name, coding='utf-8'):
        whether = Db.import_csv(path, table_name, coding)

        self.sucees_check(whether)
        if whether:
            self.export_tableName.addItem(table_name)
            self.row_delete_tableName.addItem(table_name)
            self.table_delete_tableName.addItem(table_name)
            self.alter_table_name.addItem(table_name)

    def export_check(self, table_name, path):
        whether = Db.export_csv(table_name, path)
        self.sucees_check(whether)

    def sucees_check(self, whether, cor_text='', err_text=''):
        if whether:
            if cor_text == '':
                self.cor = CorrectWindow()
            else:
                self.cor = CorrectWindow(cor_text)
            self.cor.show()
        else:
            if cor_text == '':
                self.err = ErrorWindow()
            else:
                self.err = ErrorWindow(err_text)
            self.err.show()
